package com.qingke.easyjava.jdbc.command.impl;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.qingke.easyjava.jdbc.app.BeSuperApplication;
import com.qingke.easyjava.jdbc.app.BeSuperDao;
import com.qingke.easyjava.jdbc.command.SystemCommand;
import com.qingke.easyjava.jdbc.pojo.Player;
import com.qingke.easyjava.jdbc.util.QingkeConsole;

public class SignupCommand extends SystemCommand {

	@Override
	public void execute() {
		
		BeSuperDao dao = new BeSuperDao();
		
		String username = QingkeConsole.askUserInput("Please enter your name");
		while(dao.isUsernameExists(username)) {
			QingkeConsole.println("Username hae been exist!");
			username = QingkeConsole.askUserInput("Please enter your name");
		}
		
		String password = QingkeConsole.askUserInput("Please enter your password");
		while(!validatePassword(password.trim())) {
			password = QingkeConsole.askUserInput("Please enter your password");
		}
		
		String nickname = QingkeConsole.askUserInput("Please enter your nickname");
		dao.signup(username, password,nickname);
		Player player = dao.login(username, password);
		
		BeSuperApplication.getInstance().setplayerProfile(player);
	}

	private boolean validatePassword(String password) {
		//1. length >= 6
		if(password.trim().length() < 6) {
			QingkeConsole.println("Password need at least SIX CHARACTERS!");
			return false;
		}
		
		//2. not all number 正则表达式
		Pattern numPattern = Pattern.compile("[0-9]");
		Matcher numMatcher = numPattern.matcher(password.trim());
		if(!numMatcher.find()) {
			QingkeConsole.println("Password need at least ONE NUMBER!");
			return false;
		}
		
		//3. not all  正则表达式
		Pattern wdPattern = Pattern.compile("[A-Za-z]");
		Matcher wdMatcher = wdPattern.matcher(password.trim());
		if(!wdMatcher.find()) {
			QingkeConsole.println("Password need at least ONE CHARACTER!");
			return false;
		}
		return true;
	}
}
